/*
购物车操作
作者：晴天
*/

var $_GET = (function () {
    var url = window.document.location.href.toString();
    var u = url.split("?");
    if (typeof (u[1]) == "string") {
        u = u[1].split("&");
        var get = {};
        for (var i in u) {
            var j = u[i].split("=");
            get[j[0]] = j[1];
        }
        return get;
    } else {
        return {};
    }
})();


var GoodsCart = {
    CartList: function (type = 1) {
        if (type == 1) layer.load(2, {time: 9999999});

        $.ajax({
            type: "post",
            url: "ajax.php?act=CartList",
            dataType: "json",
            success: function (data) {
                if (type == 1) layer.closeAll();
                if (data.code == 1) {
                    $(".CartCount").text('(' + data.count + ')');
                    GoodsCart.Success(data);
                    GoodsCart.GoodsRound();
                } else {
                    GoodsCart.CartNull();
                    GoodsCart.GoodsRound();
                }
            },
            error: function () {
                layer.alert('加载失败！');
            }
        });
    },
    GoodsRound: function () {
        $.ajax({
            type: "POST",
            url: "ajax.php?act=GoodsRound",
            dataType: "json",
            success: function (data) {
                if (data.code == 0) {
                    var content = '';
                    $.each(data.data, function (key, val) {
                        if (window.frames.length != parent.frames.length) {
                            var url = 'javascript:GoodsCart.iframe(\'/?mod=shop&cid=' + val.cid + '&gid=' + val.gid + '\');';
                            $(".pay40 a").attr('href', 'javascript:GoodsCart.iframe(\'/\');');
                        } else {
                            var url = '/?mod=shop&cid=' + val.cid + '&gid=' + val.gid;
                        }
                        content += '<li>\n' +
                            '          <a href="' + url + '">\n' +
                            '              <img src="' + val.image + '" style="height: ' + [$(window).width() > 460 ? '36' : '26'] + 'vh" class="proimg"/>\n' +
                            '              <p class="tit">' + val.name + '</p>\n' +
                            '              <p class="price">￥' + val.price + '<span>￥' + (val.price - 0) * 2 + '</span><img src="/assets/AppStore/images/f3.png"/></p>\n' +
                            '          </a>\n' +
                            '      </li>';
                    });
                    $("#GoodsRound").html(content);
                    layui.use('flow', function () {
                        var flow = layui.flow;
                        flow.lazyimg();
                    });
                }
            },
            error: function () {
                layer.alert('商品推荐获取失败！');
            }
        });
    },
    iframe: function (url) {
        var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
        console.log(index)
        top.location.href = url;
    },
    CartNull: function () {
        $("#CartContent").html($("#CartNull").html());
        $(".hejiBox").hide();
    },
    Success: function (data) {
        var price_all = 0;//所有订单总金额
        var select_key = '';// 选中商品
        var content = '<div class="gwc1_1" >\n' +
            '            <div class="g1 Goodsd_1">\n' +
            '                <div class="gwccheck on"></div>\n' +
            '            </div>\n' +
            '            <div class="g2">\n' +
            '                <a href="/">\n' +
            '                    <span>' + data.sitename + '</span>\n' +
            '                    <img src="/assets/AppStore/images/mre1.png"/>\n' +
            '                </a>\n' +
            '            </div>\n' +
            '        </div>';
        content += '<div class="clear"></div>\n' +
            '        <div class="gwc1_2" id="GoodsCart_1">';

        price_lei = 0;
        $.each(data.data, function (key, val) {
            select_key += '|' + key;
            if (val.price == val.GidData.price) {
                var Prics = '价格平稳';
            } else if (val.price > val.GidData.price) {
                var Prics = '<font color="#40e0d0">降价￥' + (val.price - val.GidData.price).toFixed(2) + '</font>';
            } else {
                var Prics = '<font color="#ff7f50">涨价￥' + (val.GidData.price - val.price).toFixed(2) + '</font>';
            }
            price_all += val.GidData.price;
            price_lei += val.GidData.price;
            content += '<div class="gwcone" id="CartShop_' + key + '" data-Count="' + val.GidData.Count + '" data-quota="' + val.GidData.quota + '" data-quantity="' + val.GidData.quantity + '" data-min="' + val.GidData.min + '" data-max="' + val.GidData.max + '" data-count_type="' + val.GidData.count_type + '">\n' +
                '                <div class="go1 CartSelect_1" id="Cart_' + key + '" data-price="' + val.GidData.price + '">\n' +
                '                    <div class="gwccheck on"></div>\n' +
                '                </div>\n' +
                '                <div class="go2"><a href="/?mod=shop&cid=' + val.GidData.cid + '&gid=' + val.gid + '"><img src="' + val.GidData.image + '"/></a></div>\n' +
                '                <div class="go3">\n' +
                '                    <div class="go3_1">\n' +
                '                        <a href="/?mod=shop&cid=' + val.GidData.cid + '&gid=' + val.gid + '"><p class="p1">' + val.GidData.name + '</p></a>\n' +
                '                        <p class="p2" style="text-decoration: none">' + Prics + '</p>\n' +
                '                    </div>\n' +
                '                    <div class="go3_2">\n' +
                '                        <p class="p3">' + val.conts + '</p>\n' +
                '                        <p class="p4">￥' + val.GidData.price + '</p>\n' +
                '                    </div>\n' +
                '                    <div class="go3_3">\n' +
                '                        <div class="num1" data="' + key + '">-</div>\n' +
                '                        <div class="num2" id="Sum_' + key + '">' + val.num + '</div>\n' +
                '                        <div class="num3" data="' + key + '">+</div>\n' +
                '                        <div class="del" id="' + key + '" data-price="' + val.GidData.price + '" data-image="' + val.GidData.image + '" data-name="' + val.GidData.name + '"><img src="/assets/AppStore/images/del.png"/></div>\n' +
                '                    </div>\n' +
                '                </div>\n' +
                '            </div>';
        });
        content += '</div><span class="Goods_1" data-price="' + price_lei + '"></span>';

        $("#CartContent").html(content);

        $("#price_all").text('￥' + price_all.toFixed(2));
        $("#CartContent").attr({
            'data-price': price_all, //不可变动,购物车总
            'data-price2': price_all, //可变动，购物车总
            'data-select': select_key,
        });
        $(".num1").click(function () {
            var id = $(this).attr('data');

            if ($("#CartShop_" + id).attr('data-count_type') == '-1') {
                layer.msg('此商品下单份数不可修改！');
                return false;
            }

            var min = $("#CartShop_" + id).attr('data-min') - 0; //最小下单数量！
            var max = $("#CartShop_" + id).attr('data-max') - 0; //最大下单数量！
            var quantity = $("#CartShop_" + id).attr('data-quantity') - 0; //下单数量！
            var Count = $("#CartShop_" + id).attr('data-Count') - 0; //此商品下单总数量！
            var quota = $("#CartShop_" + id).attr('data-quota') - 0; //此商品今日可用库存
            count = $("#Sum_" + id).text() - 0;
            if ((count - 1) <= 0) {
                layer.msg('最低下单一份!');
                return false;
            }

            /**
             * 执行减少份数操作！
             */
            var load = layer.load(2);
            $.ajax({
                type: "POST",
                url: "ajax.php?act=CartNum",
                data: {id: id, num: (count - 1)},
                dataType: "json",
                success: function (data) {
                    layer.closeAll();
                    if (data.code == 1) {
                        $("#Sum_" + id).text((count - 1));
                        GoodsCart.CartList(2);
                    } else {
                        layer.msg(data.msg, {icon: 2});
                    }
                },
                error: function () {
                    layer.alert('减少份数失败！');
                }
            });
        });

        $(".num3").click(function () {

            var id = $(this).attr('data');

            if ($("#CartShop_" + id).attr('data-count_type') == '-1') {
                layer.msg('此商品下单份数不可修改！');
                return false;
            }

            var min = $("#CartShop_" + id).attr('data-min') - 0; //最小下单数量！
            var max = $("#CartShop_" + id).attr('data-max') - 0; //最大下单数量！
            var quantity = $("#CartShop_" + id).attr('data-quantity') - 0; //下单数量！
            var Count = $("#CartShop_" + id).attr('data-Count') - 0; //此商品下单总数量！
            var quota = $("#CartShop_" + id).attr('data-quota') - 0; //此商品今日可用库存

            if (quota < Count) {
                layer.msg('此商品今日库存不足,仅剩！' + quota + '份<br>请减少下单数量！<br>当前您购物车共有' + Count + '份此商品！');
                return false;
            }

            count = ($("#Sum_" + id).text() - 0);
            if ((count + 1) > quota) {
                layer.msg('商品库存不足!');
                return false;
            }
            var max_sum = max / quantity; //最大下单份数
            if (count >= max_sum && min != 0 && max != 0) {
                layer.msg('此商品单次最多购买' + max_sum + '份!');
                return false;
            }

            var max_sum = max / quantity; //最大下单份数
            if (Count >= quota) {
                layer.msg('此商品今日库存不足<br>今日最多购买' + quota + '份！');
                return false;
            }

            /**
             * 执行增加份数操作！
             */
            var load = layer.load(2);
            $.ajax({
                type: "POST",
                url: "ajax.php?act=CartNum",
                data: {id: id, num: (count + 1)},
                dataType: "json",
                success: function (data) {
                    layer.closeAll();
                    if (data.code == 1) {
                        $("#Sum_" + id).text((count + 1));
                        GoodsCart.CartList(2);
                    } else {
                        layer.msg(data.msg, {icon: 2});
                    }
                },
                error: function () {
                    layer.alert('增加份数失败！');
                }
            });
        });

        $(".del").click(function () {
            var id = this.id;
            layer.open({
                title: false,
                content: '<center><font size="3" color="red">商品售价：' + $("#" + id).attr('data-price') + '元</font><br><img src="' + $("#" + id).attr('data-image') + '" width="60" height="60" style="border-radius: 0.5em;margin-top: .3em;;" /></center><br>是否要把[' + $("#" + id).attr('data-name') + ']移出购物车？',
                btn: ['确认执行', '取消'],
                btn1: function (layero, index) {
                    var load = layer.load(2);
                    $.ajax({
                        type: "POST",
                        url: "ajax.php?act=CartDet&id=" + id,
                        dataType: "json",
                        success: function (data) {
                            layer.closeAll();
                            if (data.code == 1) {
                                $("#CartShop_" + id).hide(100);
                                layer.msg(data.msg, {icon: 1});
                                setTimeout(function () {
                                    GoodsCart.CartList(2);
                                }, 500);
                            } else {
                                layer.msg(data.msg, {icon: 2});
                            }
                        },
                        error: function () {
                            layer.alert('删除失败！');
                        }
                    });
                }
            });
        });

        $(".Goodsd_1,.heji_1").click(function () {
            var PriceSum = price_all - 0; //不变数
            if ($(".Goodsd_1 div").attr('class') == 'gwccheck' || $(".heji_1 div").attr('class') == 'gwccheck') {
                //开启全部
                $(".CartSelect_1 div,.Goodsd_1 div,.heji_1 div").attr('class', 'gwccheck on');
                $("#CartContent").attr('data-price2', PriceSum);
                $("#price_all").text('￥' + PriceSum.toFixed(2));
                $(".CartCount").text('(' + data.count + ')');
                $("#CartContent").attr('data-select', select_key);
            } else {
                //关闭全部
                $(".CartSelect_1 div,.Goodsd_1 div,.heji_1 div").attr('class', 'gwccheck');
                $("#CartContent").attr('data-price2', 0);
                $("#price_all").text('￥' + 0);
                $(".CartCount").text('');
                $("#CartContent").attr('data-select', '');
            }
        });

        $(".CartSelect_1").click(function () {
            var PriceSum = price_all - 0;
            var PriceSum2 = $("#CartContent").attr('data-price2') - 0;

            var PriceKey = $("#" + this.id + " .gwccheck").attr('class');
            if (PriceKey == 'gwccheck on') {
                //需关闭
                $("#" + this.id + " .gwccheck").attr('class', 'gwccheck');
                var Prices = $("#" + this.id).attr('data-price') - 0;
                $("#CartContent").attr('data-price2', PriceSum2 - Prices);
                $("#price_all").text('￥' + ((PriceSum2 - Prices <= 0 ? 0 : PriceSum2 - Prices)).toFixed(2));
            } else {
                //需开启
                $("#" + this.id + " .gwccheck").attr('class', 'gwccheck on');
                var Prices = $("#" + this.id).attr('data-price') - 0;
                $("#CartContent").attr('data-price2', PriceSum2 + Prices);
                $("#price_all").text('￥' + (PriceSum2 + Prices).toFixed(2));
            }

            count_shop = data.data.length; //临时总数

            $(".Goodsd_1 div,.heji_1 div").attr('class', 'gwccheck');
            var counts = 0;
            var seles = '';
            for (a = 0; a < count_shop; a++) {
                var state = $("#Cart_" + a + " .gwccheck").attr('class');
                if (state == 'gwccheck on') {
                    seles += '|' + a;
                    $(".Goodsd_1 div,.heji_1 div").attr('class', 'gwccheck on');
                    ++counts;
                }
            }
            $("#CartContent").attr('data-select', seles);
            $(".CartCount").text((counts == 0 ? '' : '(' + counts + ')'));
        })
    }
    , submit: function () {
        var arr = GoodsCart.selected();
        if (arr == -1) {
            layer.msg('最少选择一件商品哦');
            return false;
        }
        $.ajax({
            type: "post",
            url: "ajax.php?act=CartSkip",
            data: {data: arr},
            dataType: "json",
            success: function (data) {
                if (data.code == 1) {
                    location.href = data.url;
                    setTimeout(function () {
                        layer.alert('<font size="4" color="#2e8b57">若未跳转付款界面,请点击下方付款按钮！</font>', {
                            title: '温馨提示!',
                            btn: ['付款'], time: 9999999, btn1: function (layero, index) {
                                location.href = data.url;
                            }
                        })
                    }, 500);
                } else layer.msg(data.msg, {icon: 2});
            },
            error: function () {
                layer.alert('加载失败！');
            }
        });
    },
    selected: function () {
        var select = $("#CartContent").attr('data-select');
        if (select == '') return -1;
        select = select.substr(1, select.length);
        var arr = select.split('|');
        return arr;
    }
    , PaySrt: function (srt) {
        var Array = srt.split('|');
        layer.load(2, {time: 9999999});
        var CartKey = $("body").attr('cartkey');
        $.ajax({
            type: "post",
            url: "ajax.php?act=CartList",
            data: {data: Array, CartKey: CartKey},
            dataType: "json",
            success: function (data) {
                if (data.code == 1) {
                    GoodsCart.PaySrtSucc(data);
                } else {
                    layer.msg(data.msg);
                    layer.closeAll();
                }
            },
            error: function () {
                layer.alert('加载失败！');
            }
        });
    },
    PaySrtSucc: function (data) {
        var price = 0;
        content = '';
        var les = data.data.length;
        $.each(data.data, function (key, val) {
            price += val['GidData']['price'];
            if (val.price == val.GidData.price) {
                var Prics = '平稳';
            } else if (val.price > val.GidData.price) {
                var Prics = '<font color="#40e0d0">降价￥' + (val.price - val.GidData.price).toFixed(2) + '</font>';
            } else {
                var Prics = '<font color="#ff7f50">涨价￥' + (val.GidData.price - val.price).toFixed(2) + '</font>';
            }

            if (val.GidData.communityId == '-1') { //自营
                var comm = '<span class="layui-badge" style="background-color: #009688">手动发货</span>';
            } else if (val.GidData.communityId == '-2') { //卡密
                var comm = '<span class="layui-badge" style="background-color: #F57F17">自动发货</span>';
            } else if (val.GidData.communityId == '-3') { //Curl
                var comm = '<span class="layui-badge " style="background-color: #FF9800">自动发卡</span>';
            } else {
                var comm = '<span class="layui-badge" style="background-color: #00C853">自动发货</span>';
            }

            content += '<div ' + (window.innerWidth > 480 ? 'class="layui-col-sm' + (les == 1 ? '12' : '6') + '" style="margin-top: 0.7em;"' : 'class="layui-col-xs12" style="padding: 0.1em 0.8em 0 0.8em;margin-bottom: 0.9em"') + '>\n' +
                '                <div class="layui-card" style="border-radius: 0.5em">\n' +
                '                    <div class="layui-card-header">\n' +
                '                        下单份数：' + val['num'] + '份\n' +
                '                        <span style="float: right;">' + comm + '</span>\n' +
                '                    </div>\n' +
                '                    <div class="layui-row layui-col-space8">\n' +
                '                        <div class="layui-col-xs2">\n' +
                '                            <div style="border-radius: 0.5em;width: 3em;text-align: center;height: 3em;line-height: 3em;background-color: #fff;color:white;margin: 0.8em;box-shadow: 3px 3px 16px #eee">\n' +
                '                                <img lay-src="' + val['GidData']['image'] + '" style="width: 100%;border-radius: 0.5em"/>\n' +
                '                            </div>\n' +
                '                        </div>\n' +
                '                        <div class="layui-col-xs10">\n' +
                '                            <div class="layui-card-header"\n' +
                '                                 style="font-size: 1.1em;line-height: 2em;height:auto;">\n' +
                '                                ' + val['GidData']['name'] + '\n' +
                '                            </div>\n' +
                '                            <div class="layui-card-body information layui-text" style="line-height: 2em">\n' +
                '                                <p><span onclick="layer.msg(\'份数×数量=购买数量\')">购买数量</span><span\n' +
                '                                            style="float: right;">' + val['GidData']['quantity'] * val['num'] + '个</span></p>' +
                '                               <p>价格趋势 <span style="float: right;">' + Prics + '</span></p>\n' +
                '                                <p>货币兑换<span\n' +
                '                                            style="float: right;">' + val['GidData']['points'] + '</span>\n' +
                '                                </p>\n' +
                '<p>' + val['conts'] + '</p>' +
                '                                <p style="float: right;margin-top: 0.8em;font-size: 1.05em">商品售价：<font\n' +
                '                                            color="#ff4500"\n' +
                '                                            style="font-size: 1.1em">￥' + val['GidData']['price'] + '</font>\n' +
                '                                </p>\n' +
                '                            </div>\n' +
                '                        </div>\n' +
                '                    </div>\n' +
                '                </div>\n' +
                '            </div>';
        });
        $("#sum").text(data.data.length);
        $("#Price").text(price.toFixed(2));
        $("#Content").html(content);
        layer.closeAll();
        layui.use('flow', function () {
            var flow = layui.flow;
            flow.lazyimg();
        });
    },
    PaySubmit: function (data) {
        var Array = data.split('|');
        var paytype = $("input[name=pay]:checked").val();
        mode = 'alipay';
        type = 1;
        if (paytype == undefined) {
            swal({
                title: '注意',
                type: 'warning',
                html: '<h4>请选择付款方式！</h4>',
                confirmButtonText: '好的',
            });
            return false;
        }
        switch (paytype) {
            case '1'://支付宝
                mode = 'alipay';
                break;
            case '2': //微信
                mode = 'wxpay';
                break;
            case '3': //QQ
                mode = 'qqpay';
                break;
            case '4': //余额
                type = 2;
                break;
            case '5': //积分
                type = 3;
                break;
        }
        var index = layer.msg('操作中,请稍后...', {icon: 16, time: 9999999});
        var CartKey = $("body").attr('cartkey');
        $.ajax({
            type: "post",
            url: "/ajax.php?act=CartPay",
            data: {
                data: Array,
                mode: mode,
                type: type,
                CartKey: CartKey,
            },
            dataType: "json",
            success: function (data) {
                layer.close(index);
                if (data.code == 1) {
                    var inst = layer.alert(data.msg, {
                        title: '温馨提示',
                        btn: ['查看订单', '返回'], time: 9999999, btn1: function (layero, index) {
                            location.href = '/?mod=query';
                        },
                        btn2: function (layero, index) {
                            location.href = '/?mod=cart';
                        }
                    })
                } else if (data.code == 2) {
                    if (window.frames.length != parent.frames.length) {
                        GoodsCart.iframe(data.url);
                        setTimeout(function () {
                            layer.alert('<font size="4" color="#2e8b57">若未跳转付款界面,请点击下方付款按钮！</font>', {
                                title: '温馨提示!',
                                btn: ['付款'], time: 9999999, btn1: function (layero, index) {
                                    GoodsCart.iframe(data.url);
                                }
                            })
                        }, 500);
                    } else {
                        location.href = data.url;
                        setTimeout(function () {
                            layer.alert('<font size="4" color="#2e8b57">若未跳转付款界面,请点击下方付款按钮！</font>', {
                                title: '温馨提示!',
                                btn: ['付款'], time: 9999999, btn1: function (layero, index) {
                                    location.href = data.url;
                                }
                            })
                        }, 500);
                    }
                } else {
                    layer.alert(data.msg, {
                        icon: 2, title: '温馨提示', btn: '返回', btn1: function (layero, index) {
                            location.href = '/?mod=cart';
                        }
                    });
                }
            },
            error: function () {
                layer.alert('加载失败！');
            }
        });
    }
}